from django import forms
from django.core.exceptions import ValidationError

from rbac.models import UserInfo


class UserInfoAddModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserInfoAddModelForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    confirm_password = forms.CharField(label='确认密码')

    class Meta:
        model = UserInfo
        fields = ['username', 'password', 'confirm_password', 'email']

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if password != confirm_password:
            raise ValidationError('两次输入密码不一致，请重新输入')
        return confirm_password


class UserInfoEditModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserInfoEditModelForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = UserInfo
        fields = ['username', 'email']


class UserInfoResetPasswordModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(UserInfoResetPasswordModelForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    confirm_password = forms.CharField(label='确认密码')

    class Meta:
        model = UserInfo
        fields = ['password', 'confirm_password']

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if len(password) < 8:
            raise ValidationError('密码长度不能小于8位')
        if password != confirm_password:
            raise ValidationError("两次密码输入不一致，请重新输入")
        return confirm_password
